﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Drawing;
using Microsoft.Practices.Unity;

namespace XClient.Controls
{
    public class TryIcon
    {
        #region · Fields ·

        private NotifyIcon          notifyIcon;
        private ContextMenuStrip    contextMenu;
        private Window              window;
        private bool                isClosing;
        private IUnityContainer     container;

        #endregion

        #region · Properties ·

        public Icon Icon
        {
            get { return this.notifyIcon.Icon; }
            set { this.notifyIcon.Icon = value; }
        }

        #endregion

        #region · Constructors ·

        public TryIcon(IUnityContainer container)
        {
            this.container = container;
        }

        #endregion

        #region · Methods ·

        public void Initialize(Window window, Icon icon)
        {
            this.window         = window;
            this.notifyIcon     = new NotifyIcon();
            this.contextMenu    = new ContextMenuStrip();

            ToolStripMenuItem tryIconMenuExit = new ToolStripMenuItem();
            tryIconMenuExit.Text = "Exit";
            tryIconMenuExit.Click += new EventHandler(tryIconMenuExit_Click);

            this.contextMenu.Items.Add(tryIconMenuExit);

            this.notifyIcon.Icon = icon;
            this.notifyIcon.ContextMenuStrip = this.contextMenu;
            this.notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);

            window.Closing += new System.ComponentModel.CancelEventHandler(window_Closing);

            this.notifyIcon.Visible = true;
        }

        #endregion

        #region · Methods ·

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.window.Visibility  = Visibility.Visible;
        }

        private void tryIconMenuExit_Click(object sender, EventArgs e)
        {
            this.isClosing = true;
            this.window.Close();
        }

        private void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!this.isClosing)
            {
                e.Cancel = true;
                this.window.Visibility = Visibility.Hidden;
            }
            else
            {
                this.notifyIcon.Dispose();
            }
        }

        #endregion
    }
}
